<?php
declare(strict_types=1);

namespace App\Utils\Other\Router;

use Hyperf\HttpServer\Router\Router as RouterFactory;
use Hyperf\Collection\Arr;

/**
 * @method static void addRoute($httpMethod, string $route, $handler, array $options = [])
 * @method static void addGroup($prefix, callable $callback, array $options = [])
 * @method static void get($route, $handler, array $options = [])
 * @method static void post($route, $handler, array $options = [])
 * @method static void put($route, $handler, array $options = [])
 * @method static void delete($route, $handler, array $options = [])
 * @method static void patch($route, $handler, array $options = [])
 * @method static void head($route, $handler, array $options = [])
 */
Class Router {

    public static function __callStatic($name, $arguments)
    {
        return RouterFactory::$name(...$arguments);
    }

    /**
     * 资源路由
     * @param string $route
     * @param string $classPath
     * @param array $options
     * @param array $action
     */
    public static function resource(string $route, string $classPath, array $options=[], array $addAction=[])
    {
        $actions = [
            'index' => [
                'type' => 'get',
                'path' => ''
            ],
            'page' => [
                'type' => 'get',
                'path' => '/page'
            ],
            'create' => [
                'type' => 'get',
                'path' => '/create'
            ],
            'save' => [
                'type' => 'post',
                'path' => ''
            ],
            'read' => [
                'type' => 'get',
                'path' => '/{id}'
            ],
            'edit' => [
                'type' => 'get',
                'path' => '/{id}/edit'
            ],
            'update' => [
                'type' => 'put',
                'path' => '/{id}'
            ],
            'delete' => [
                'type' => 'delete',
                'path' => '/{id}'
            ],
            'destroy' => [
                'type' => 'delete',
                'path' => ''
            ]
        ];
        $actions = array_merge($addAction, $actions);

        foreach ($actions as $action => $handler) {
            if (Arr::get($options, 'only') && !in_array($action, $options['only'])) {
                continue;
            }
            if (!method_exists($classPath, $action)) {
                continue;
            }
            $type = $handler['type'];
            RouterFactory::$type($route.$handler['path'], [$classPath, $action], $options);
        }
    }
}